<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_Model extends CI_Model {
	var $tableName;
	var $prefix;

	function __construct() {
		parent::__construct();
	}

	function insert($data) {

		foreach($data as $key => $val) {
			if(!is_null($val)) {
				$data[$key] = trim($val);
			}
		}
		if($this->db->insert($this->tableName, $data)) {
			$id = $this->db->insert_id();
			/*
			$log = array (
				"log_usr_id" => (($this->session->userdata("usrId"))?($this->session->userdata("usrId")):(NULL)),
				"log_table" => $this->tableName,
				"log_type" => "INS",
				"log_rec_id" => $id
			);
			$logChanges = array();
			foreach($data as $key => $value) {
				$logChanges[] = "<".$key.">".((is_null($value))?("NULL"):($value))."</".$key.">";
			}
			$log["log_changes"] = implode("", $logChanges);
			$this->db->set("log_date", "NOW()", FALSE);
			$this->db->insert("sys_log", $log);
			$this->db->cache_delete_all();
			*/
			return $id;
		}
	}

	function update($id, $data) {

		foreach($data as $key => $val) {
			if(!is_null($val)) {
				$data[$key] = trim($val);
			}
		}

		$this->db->select("*");
		$this->db->from($this->tableName);
		$this->db->where($this->prefix."_id", $id);
		$result = $this->db->get();
		$old = $result->row();

		$changes = array();
		foreach($data as $key => $value) {
			if($old->$key != $value) {
				$changes[] = "<".$key.">".((is_null($value))?("NULL"):($value))."</".$key.">";
			}
		}

		if(!empty($changes)) {
			$this->db->where($this->prefix."_id", $id);
			if($this->db->update($this->tableName, $data)) {
				/*
				$log = array (
					"log_usr_id" => (($this->session->userdata("usrId"))?($this->session->userdata("usrId")):(NULL)),
					"log_table" => $this->tableName,
					"log_type" => "UPD",
					"log_rec_id" => $id
				);
					$log["log_changes"] = implode("", $changes);
					$this->db->set("log_date", "NOW()", FALSE);
					$this->db->insert("sys_log", $log);
					$this->db->cache_delete_all();
				*/
			}
		}
	}

	function delete($id) {

		$this->db->where($this->prefix."_id", $id);
		if($this->db->update($this->tableName, array($this->prefix."_del" => time())) AND $this->db->affected_rows()) {
			/*
			$log = array (
				"log_usr_id" => (($this->session->userdata("usrId"))?($this->session->userdata("usrId")):(NULL)),
				"log_table" => $this->tableName,
				"log_type" => "DEL",
				"log_rec_id" => $id
			);
			$this->db->set("log_date", "NOW()", FALSE);
			$this->db->insert("sys_log", $log);
			$this->db->cache_delete_all();
			*/
		}
	}
}

?>